/*
 * @Author: fzs
 * @Date: 2018-12-18 16:17:55
 * @LastEditors: fzs
 * @LastEditTime: 2018-12-18 16:19:12
 * @Description:  事件通讯 (使用单例模式的服务可以使用)
 */

import { Injectable } from '@angular/core';
import { Subject, Subscription } from 'rxjs/index';

@Injectable()
export class EventsService {
  private events = {};
  /**
   * 订阅事件
   * @param eventName 事件名称
   * @param next 回调函数
   */
  addSubscribe(eventName, next): Subscription {
    if (this.events[eventName]) {
      this.events[eventName].unsubscribe();
    }
    this.events[eventName] = new Subject();
    return this.events[eventName].subscribe(next);
  }
  /**
   * 根据事件名称触发订阅
   * @param eventName 事件名称
   * @param value 传过去的值
   */
  next(eventName, value?) {
    if (this.events[eventName]) {
      this.events[eventName].next(value);
    }
  }

  /**
   * 卸载指定的事件
   * @param eventName 事件名称
   */
  unsubscribe(eventName) {
    if (this.events[eventName]) {
      this.events[eventName].unsubscribe();
    }
    delete this.events[eventName];
  }
  /**
   * 卸载所有订阅的事件
   */
  unAllSubscribe() {
    for (const key of Object.keys(this.events)) {
      this.events[key].unsubscribe();
    }
    this.events = {};
  }
}
